package com.store.app.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.store.app.BaseActivity;
import com.store.app.ExitApplication;
import com.store.app.MainActivity;
import com.store.app.R;
import com.store.app.bean.CouponGoCashBean;
import com.store.app.http.Stores;
import com.store.app.http.Submit;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.pay.alipay.Alipay;
import com.store.app.pay.alipay.AlipayModel;
import com.store.app.pay.alipay.AlipayState;
import com.store.app.utils.GoToLogin;
import com.store.app.utils.MoneyUtil;
import com.store.app.utils.SettingData;
import com.store.app.utils.ToastUtils;
import com.store.app.utils.Utils;
import com.store.app.wxapi.WXOrderbean;
import com.store.app.wxapi.WetchatPay;

import org.apache.http.NameValuePair;
import org.apache.http.conn.util.InetAddressUtils;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * 现金充值支付页面
 */
public class CashPaymentActivity extends BaseActivity implements AlipayState,IOnHttpListener {


    //应付金额
    private String money,phone,memberId;
    //手机号码
    private TextView tv_phone;
    //充值金额
    private TextView tv_num;

    //提交
    private TextView tv_submit;
    //支付选择
    private RelativeLayout relat1, relat2, relat3;
    //账户余额
    private TextView tv_yuer;
    //支付选择imgview
    private ImageView img1, img2, img3;
    //支付选择 1 余额 2支付宝 3微信
    private int pay_type = 2;
    //支付宝请求订单获取的model
    private AlipayModel model;
    private WXOrderbean wxOrderbean;
    private String dataStr;
    private MyReceiver myReceiver;
    private GoToLogin goToLogin;
    private TextView title;
    private NetRequest netRequest;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ExitApplication.getInstance().addActivity(this);
        goToLogin = new GoToLogin(this);
        netRequest = new NetRequest(this);
        phone = getIntent().getStringExtra("phone");
        money = getIntent().getStringExtra("money");
        memberId= getIntent().getStringExtra("member_id");
        setContentView(R.layout.activity_cashpayment);
        initView();
        initData();
        initListeners();
        myReceiver = new MyReceiver();
        registerReceiver(myReceiver, new IntentFilter("FINISH"));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myReceiver);
    }

    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                //支付宝支付
                case 1:
                    new Alipay(CashPaymentActivity.this,  model, CashPaymentActivity.this).pay();
//                    new Alipay(ConfirmPaymentActivity.this, bean.getTitle(), bean.getDesc1(),"0.01", model,ConfirmPaymentActivity.this).pay();
                    break;
                //余额支付成功
                case 2:
                    dismissProgressDialog();
                    Toast.makeText(CashPaymentActivity.this, "零钱充值成功！", Toast.LENGTH_LONG).show();
                    new QueryInfo().start();
                    finish();
                    EventBus.getDefault().post(new CouponGoCashBean(1));
                    break;
                //刷新余额成功
                case 3:
                    tv_yuer.setText(Stores.cash_balance + "");
                    break;
                //生成微信支付订单成功，调用给微信支付
                case 4:

//                    showToast("获取订单支付信息成功："+wxOrderbean.getAppid()+"dataStr:"+dataStr);
                    Log.v("zyl", "开启微信支付");

                    if (wxOrderbean != null) {
                        WetchatPay wetchatPay = new WetchatPay(CashPaymentActivity.this, wxOrderbean);
                        wetchatPay.pay();
//                        showToast("实体不为空：" + wetchatPay.toString());
                    }
                    break;
                case 5:
                    showToast("微信支付失败,网络波动");
                    break;

                case 9:
                    showToast("微信支付失败,网络不通");
                    break;
                case 7:
                    dismissProgressDialog();
                    showToast("网络不通，支付失败");
                    break;
                //订单支付失败
                case 8:
                    showToast(msg.obj.toString());
                    break;
            }
        }
    };

    @Override
    public void finish() {
        dismissProgressDialog();
        super.finish();
    }

    private void initListeners() {
        tv_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Utils.isFastClick()) {
                    return;
                }
                if (pay_type == 1) {
                    if (!MoneyUtil.moneyComp(Stores.cash_balance + "", money)) {
                        Toast.makeText(CashPaymentActivity.this, "零钱余额不足,请选择其他支付方式！", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    showConfirmDialog("", "确定为"+phone+"充值"+money+"元 ?", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            showProgressDialog("", "支付中...", true);
                            if(!TextUtils.isEmpty(MainActivity.member_id)&&!TextUtils.isEmpty(memberId)){
                                netRequest.requestMoneyPay(1,money,MainActivity.member_id,memberId);
                            }
                        }
                    });
                } else if (pay_type == 2) {
                    //支付宝的支付方式 ZFFS_01

                    new GetOrder(1).start();
                } else if (pay_type == 3) {
                    //微信支付

                    boolean ifInstall = Utils.isWXAppInstalledAndSupported(CashPaymentActivity.this);
                    if (ifInstall) {
                        new GetOrder(2).start();
                    } else {
                        showToast("尚未安装微信,请检查您的手机");
                        return;
                    }

                }
            }
        });
        findViewById(R.id.public_ll_return).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        relat1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pay_type = 1;
                img1.setBackgroundResource(R.drawable.pay_circle);
                img2.setBackgroundResource(R.drawable.pay_circle_gray);
                img3.setBackgroundResource(R.drawable.pay_circle_gray);

            }
        });
        relat2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pay_type = 2;
                img1.setBackgroundResource(R.drawable.pay_circle_gray);
                img2.setBackgroundResource(R.drawable.pay_circle);
                img3.setBackgroundResource(R.drawable.pay_circle_gray);
            }
        });
        relat3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pay_type = 3;
                img1.setBackgroundResource(R.drawable.pay_circle_gray);
                img2.setBackgroundResource(R.drawable.pay_circle_gray);
                img3.setBackgroundResource(R.drawable.pay_circle);
            }
        });


    }

    private void initData() {
        tv_phone.setText(phone);

        tv_num.setText(money);
        String s_yuer = Stores.cash_balance + "";
        if (!TextUtils.isEmpty(s_yuer)) {
            tv_yuer.setText(s_yuer);
        }
    }

    private void initView() {
        tv_phone = (TextView) findViewById(R.id.tv_phone);
        tv_num = (TextView) findViewById(R.id.tv_money);
        tv_submit = (TextView) findViewById(R.id.submit);
        relat1 = (RelativeLayout) findViewById(R.id.pay_relat1);
        relat2 = (RelativeLayout) findViewById(R.id.pay_relat2);
        relat3 = (RelativeLayout) findViewById(R.id.pay_relat3);
        tv_yuer = (TextView) findViewById(R.id.yuer);
        img1 = (ImageView) findViewById(R.id.pay_check_1);
        img2 = (ImageView) findViewById(R.id.pay_check_2);
        img3 = (ImageView) findViewById(R.id.pay_check_3);
        title=(TextView) findViewById(R.id.tvTitle);
        title.setText("零钱充值");
    }

    @Override
    public void onAlipaySuccess() {
        Log.v("zyl", "支付宝支付成功");
        finish();
        EventBus.getDefault().post(new CouponGoCashBean(1));
    }

    @Override
    public void onAlipayFail() {
        Log.v("zyl", "支付宝支付失败");
    }

    @Override
    public void onAfinalFail() {

    }

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
        if(requestId ==1){
            handler.sendEmptyMessage(2);
        }
    }

    @Override
    public void onExecuteFail(int requestId, String msg) {
        ToastUtils.showTextToast(CashPaymentActivity.this,msg);
    }

    /**
     * 订单支付接口
     */
    public class GetOrder extends Thread {
        //1支付宝 2微信
        private int type;

        public GetOrder(int type) {
          this.type=type;
        }

        public void run() {
            try {

                JSONObject params = new JSONObject();
                params.put("data_source", "SJLY_02");
                if(type==1) {
                    params.put("payment_way_key", SettingData.PAYMENT_WAY_01);
                }else if(type==2){
                    params.put("payment_way_key", SettingData.PAYMENT_WAY_02);
                }
                params.put("detail", "现金充值");
                params.put("amount", money);                      //金额
                params.put("currency_code", "CNY");                      //支付方式
                params.put("buyer_id", memberId);               //店东的id
                params.put("seller_id", "10000001");         //每天惠的id是啥
                params.put("out_trade_body", params.toString());
                params.put("flag", "new");                   //微信支付和支付宝直接获取支付信息
                List<NameValuePair> pairList = new ArrayList<NameValuePair>();
                pairList.add(new BasicNameValuePair("params", params.toString()));
                pairList.add(new BasicNameValuePair("service", "finance.balanceRecharge"));
                pairList.add(new BasicNameValuePair("user_token", MainActivity.user_token));
                String sign = Submit.genPackageSignUser(pairList);
                pairList.add(new BasicNameValuePair("sign", sign));

                JSONObject obj = Submit.submit(pairList, Stores.http + "/openapi/finance");
                String rsp_code = obj.getString("rsp_code");
                if (rsp_code.equals("succ")) {
                    dataStr = obj.getString("data");

                    if(type==1){
                        JSONObject jsonObject=new JSONObject(dataStr);
                        model = new AlipayModel();
                        model.setAlipay_params(jsonObject.getString("alipay_params"));
                        handler.sendEmptyMessage(1);
                    }else if(type==2){
                        JSONObject jsonObject = new JSONObject(dataStr);
                        Log.v("zyl", "微信生成订单成功:" + dataStr);
                        wxOrderbean = new WXOrderbean();
                        wxOrderbean.setTransaction_no(jsonObject.getString("transaction_no"));
                        wxOrderbean.setTimestamp(jsonObject.getString("timestamp"));
                        wxOrderbean.setSign(jsonObject.getString("sign"));
                        wxOrderbean.setPartnerid(jsonObject.getString("partnerid"));
                        wxOrderbean.setPackageX(jsonObject.getString("package"));
                        wxOrderbean.setNoncestr(jsonObject.getString("noncestr"));
                        wxOrderbean.setAppid(jsonObject.getString("appid"));
                        wxOrderbean.setPrepayid(jsonObject.getString("prepayid"));
                        handler.sendEmptyMessage(4);
                    }
                } else {
                    String errorMsg = obj.getString("error_msg");
                    Message msg = Message.obtain();
                    msg.what = 8;
                    msg.obj = errorMsg;
                    if(errorMsg.contains("token")){
                        goToLogin.setGoToLogin();
                    }else{
                        handler.sendMessage(msg);
                    }
                    Log.v("zyl", "订单支付失败:" + obj.getString("error_msg"));
                }
            } catch (Exception e) {
                handler.sendEmptyMessage(7);
                e.printStackTrace();
            }
        }
    }



    public class QueryInfo extends Thread {
        public QueryInfo() {

        }

        public void run() {
            try {
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("app_token",
                        MainActivity.app_token));
                JSONObject paramsone = new JSONObject();
//						paramsone.put("member_id", MainActivity.member_id);
                paramsone.put("member_id", MainActivity.member_id + "");
                params.add(new BasicNameValuePair("params", paramsone
                        .toString()));
                params.add(new BasicNameValuePair("service",
                        "finance.memberAssetFind"));
                String sign = Submit.genPackageSign(params);
                params.add(new BasicNameValuePair("sign", sign));
                JSONObject obj = Submit.submit(params, Stores.http + "/openapi/finance");

                String result = obj.getString("rsp_code");
                if (result.equals("succ")) {
                    Log.v("zyl", "查询余额信息成功:" + obj.getString("data"));
                    JSONObject jsonObject = new JSONObject(obj.getString("data"));
                    int vo = Integer.parseInt(jsonObject.getString("voucher_balance"));
                    double banlance = Double.parseDouble(jsonObject.getString("cash_balance"));
                    Stores.cash_balance = banlance;
                    Stores.voucher_balance = vo;
                    Stores.gold = jsonObject.getString("gold");
                    Log.v("zyl", "查询到的金币：" + Stores.gold);
                    Log.v("zyl", "Stores.voucher_balance:" + Stores.voucher_balance);
                    handler.sendEmptyMessage(3);
                } else {
                    if(goToLogin.setGoToLogin(obj)){

                    }
                    Log.v("zyl", "查询余额信息失败");
                }
            } catch (Exception e) {
                Log.v("zyl", "网络不通");
            }

        }
    }
    public static String getLocalIpAddress() {
        try {
            Enumeration ex = NetworkInterface.getNetworkInterfaces();

            while(ex.hasMoreElements()) {
                NetworkInterface intf = (NetworkInterface)ex.nextElement();
                Enumeration enumIpAddr = intf.getInetAddresses();

                while(enumIpAddr.hasMoreElements()) {
                    InetAddress inetAddress = (InetAddress)enumIpAddr.nextElement();
                    if(!inetAddress.isLoopbackAddress() && InetAddressUtils.isIPv4Address(inetAddress.getHostAddress())) {
                        String str = inetAddress.getHostAddress();
                        if(!TextUtils.isEmpty(str)) {
                            return str;
                        }

                        return "192.168.0.1";
                    }
                }
            }
        } catch (SocketException var5) {
            var5.printStackTrace();
        }

        return "192.168.0.1";
    }



    /**
     * 微信支付成功之后发送一个广播过来关闭页面
     */
    private class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Log.v("zyl", "接收到广播");
            finish();
            EventBus.getDefault().post(new CouponGoCashBean(1));
        }
    }
}
